<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\api\service\message;
use app\common\controller\AdminBaseController;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\CostName;
use app\common\model\tang\CostRule;
use app\common\model\tang\CostSectionPay;
use app\common\model\tang\Merchant;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\Cost as CostModel;
use app\common\model\tang\CostType;
use app\common\model\tang\ReleaseUser;
use app\common\model\tang\SendConfig;
use app\common\model\tang\SendConfigLog;
use app\common\model\tang\StaffRule;
use app\common\model\tang\SubjectList;
use think\facade\Config;
use think\facade\Db;
use think\facade\Queue;

class Cost extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new CostModel();
    }

    public function index()
    {
        if (IS_AJAX){
            $where=[['type','notin',[4,5]]];  // ,
            return $this->model->getAdminPageData($this->param, 'id desc',$where);
//            return $this->model->getAdminPageData($this->param, 'id desc',[]);
        }
        $merchant_list =getMerchant();
        $cost_type =\app\common\model\tang\CostType::select();
        //获取菜单列表
        $this->assign(compact("merchant_list","cost_type"));
        return $this->fetch();
    }
    public function export()
    {
        $where=[['type','notin',[4,5]]];  // ,
        $this->model->getExportData($this->param, 'id desc',$where);
    }
    public function payDetail(){
        $id = $this->request->param('id');
        if (empty($id)) {
            return self::ajaxResult([],0,1,'参数有误');
        }
        $all_amount = (new \app\common\model\tang\Cost())->where(['id'=>$id])->value('all_amount');
        $list = (new CostSectionPay())->where('cost_id',$id)->select();
        $data['list'] = $list;
        $data['all_amount'] = $all_amount/100;
        $this->assign('data',$data );
        return $this->fetch();
    }
    public function getCostType()
    {
        $param = $this->request->param();
        $cost_type    = intval($param['cost_type']);
        $amount      = $param['amount'];  //  金额
        if(!empty($param['service_charge_rate'])){
            $service_charge_rate = $param['service_charge_rate'];  //  手续费  %
        }
        $cost_type_list = (new CostType())->where('pid','=',$cost_type)->field('id,type,is_carry_down,cost_name,cost_sn,tax_sn,tax_rate,tax,cost_money,th_money')->select()->toArray();
        if($amount<=0){
            return self::ajaxResult([],0,1,'缴费金额不合法');
        }
        if (empty($cost_type)){
            return self::ajaxResult([],0,1,'缴费类型不存在');
        }
        $return = [] ;
        if(!empty($cost_type_list)){
            $k = 0 ;
            $data = [] ;
            foreach ($cost_type_list as  $v){
                $k++ ;

                if($v['is_carry_down']==1){  // 转结存
                    $TaxMoneyArr = [
                        'tax_money' => 0, // 税率金额
                        'money'     => $amount, // 收入金额
                        'z_money'   => $amount,  // 总金额
                    ] ;
                }else{
                    if($v['tax']==1){
                        $TaxMoneyArr = TaxMoney($amount,1,$v['tax_rate']);
                    }else{
                        $TaxMoneyArr = [
                            'tax_money' => 0, // 税率金额
                            'money'     => $amount, // 收入金额
                            'z_money'   => $amount,  // 总金额
                        ] ;
                    }
                }
                $data[] = [
                    'id'        => $v['id'],
                    'cost_name' => $v['cost_name'],
                    'type'      => $v['type'],
                    'cost_sn'   => $v['cost_sn'], // 收费科目
                    'tax_sn'    => $v['tax_sn'],  // 税率科目
                    'unitprice' => $amount,
                    'tax_rate'  => $v['tax_rate'],  // 税率
                    'tax_money' => $TaxMoneyArr['tax_money'], // 税率金额
                    'money'     => round($TaxMoneyArr['money'],2), // 收入金额
                    'z_money'   => round($TaxMoneyArr['money']+$TaxMoneyArr['tax_money'],2),  // 总金额
                    'is_carry_down'        => $v['is_carry_down'] // 是否转结存
                ];
            }
            if(!empty($service_charge_rate)){
                $service_charge_money = round($amount * $service_charge_rate,2);
                $data[$k] = [
                    'id'        => 0,
                    'cost_name' => '手续费',
                    'type'      => '2',
                    'cost_sn'   =>  '',
                    'tax_sn'    =>  '',
                    'unitprice' => 0,
                    'tax_rate'  => 0,  // 税率
                    'tax_money' => 0, // 税率金额
                    'money'     => $service_charge_money, // 收入金额
                    'z_money'   => $service_charge_money,  // 总金额
                    'is_carry_down'        => 0 // 是否转结存
                ];
            }
            $service_charge_money = !empty($service_charge_money) ? $service_charge_money:0 ;
            $z_reality_money = round($service_charge_money + $amount ,2);
            $return = [
                'data'     => $data,
                'service_charge_money'  => $service_charge_money,
                'z_money'  => $z_reality_money
            ];
        }
        return self::ajaxResult($return,0,0,'success');
    }
    /**
     * 读取催费记录
     */
    public function see(){
        $param = $this->param;
        $result = (new SendConfigLog())->where('cost_id', '=', $param['id'])->select();
        if($result->isEmpty()){
            $this->assign('list',[] );
        }else{
            $result =$result->toArray();
            foreach ($result as $k=>$v){
                $result[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
            $this->assign('list',$result );
        }
        return $this->fetch();
    }
    /**
     * 退费
     */
    public function costRefund(){
        $param = $this->param;
        $info = $this->model->find($param['ids']);
        $balanceModel = new BalanceLog();
        if (empty($info)) {
            return self::ajaxResult([],0,1,'费用单不存在');
        }
        if ($info['pay_status']!=1) {
            return self::ajaxResult([],0,1,'费用单未交费');
        }
        if ($info['pay_status']==-1) {
            return self::ajaxResult([],0,1,'费用单已退费');
        }
        $merchantModel = new Merchant();
        Db::startTrans();
        try {
            $this->model->update(['pay_status'=>-1],['id'=>$param['ids']]);
            $balanceData['merchant_id'] = $info['merchant_id'];
            $balanceData['amount'] = $info['all_amount'];
            $balanceData['is_top_up'] = 1;
            $balanceData['edit'] = 1;
            $balanceData['status'] = 1;
            $balanceData['create_time'] = time();
            $balanceData['update_time'] = time();
            $balanceData['charge_time'] = time();
            $balanceData['remark'] ='物业侧退款冲入余额';
            $merchantModel->where('id', $info['merchant_id'])->inc('balance',$info['all_amount'])->update();
            $balanceModel->save($balanceData);
            Db::commit();
            return self::JsonReturn("退费成功");
        }catch (\Exception $exception){
            Db::rollback();
            return self::JsonReturn($exception->getMessage(),0);
        }


    }
    /**
     *催费
     */
    public function rushFee(){
        $param = $this->request->param();
        $this->assign('id',$param['id']);
        return $this->fetch();
    }
    /**
     *催费
     */
    public function void(){
        $param = $this->request->param();
        if(empty($param)){
            return parent::JsonReturn('作废账单不能为空', 0);
        }
        $update = $this->model->whereIn('id',$param['ids'])->update(['is_void'=>2]);
        if($update){
            return self::ajaxResult([],0,0,'作废成功');
        }else{
            return self::ajaxResult([],0,1,'作废失败');
        }


    }

    /**
     * 加入队列异步通知催费
     */
    public function addPush(){
        $id = $this->request->post('id');
        $password = $this->request->post('password');
        $sendPwd = (new SendConfig())->find(1);
        if($password!=$sendPwd['password']){
            return self::ajaxResult([], 0, -1, '密码错误');
        }
        $costInfo = $this->model->with(['merchant','costType'])->where('id', 'in', $id)->select()->toArray();
        foreach ($costInfo as $k=>$v){
            if(!empty($v['merchant']['openid'])){
                //加入日志
                $model = (new SendConfigLog());
                if($model->where('cost_id',$v['id'])->where('type',1)->count()<$sendPwd['most_send']){
                    $ConfigLog['cost_id'] = $v['id'];
                    $ConfigLog['merchant_id'] = $v['merchant']['id'];
                    $ConfigLog['name'] = $v['merchant']['company'];
                    $ConfigLog['openid'] = $v['merchant']['openid'];
                    $ConfigLog['create_time'] = time();
                    $result = $model->insertGetId($ConfigLog);
                    if($result){
                        if(empty($v['merchant']['name'])||$v['merchant']['name']=='-'){
                            $name = $v['merchant']['company'];
                        }else{
                            $name = $v['merchant']['name'];
                        }
                        $data = [
                            'logId'=>$result,
                            'openid'=> $v['merchant']['openid'],
                            'amount'=>$v['amount']/100,
                            'order_sn'=>$v['order_sn'],
                            'cost_name'=>$v['costType']['cost_name'],
                            'end_time'=>date('Y-m-d',$v['start_time']).'~'.date('Y-m-d',$v['end_time']),
                            'name' =>$name
                        ];
                        $this->SendMessage($data);
                    }
                }
            }

        }
        return self::ajaxResult([], 0, 1, '催费成功');
    }

    public function SendMessage($data)
    {
        // 1.当前任务由哪个类来负责处理
        // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
        $jobHandlerClassName = 'app\admin\controller\queue\AutoMessage';
        // 2.当任务归属的队列名称，如果为新队列，会自动创建
        // 这个队列名称自由建立，最好和业务相关且不能重复，不然你懂的
        $jobQueueName = "sendMessage";
        // 3.当前任务所需业务数据，不能为resource类型，其实转换成数组就行，最终都会转化为json形式的字符串，这个数据是测试数据，自己的数据自己进行组装
        Queue::push($jobHandlerClassName, $data, $jobQueueName);

    }

    public function ServiceCharge()
    {
        $id = $this->request->param("id/d");//父id
        if (empty($id)){
            return self::ajaxResult([],0,1,'fail');
        }
        $service_charge = (\app\common\model\tang\SubjectList::where(['id'=>$id])->value('rate'))/100;
        return self::ajaxResult(['service_charge'=>$service_charge],0,0,'success');
    }
    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:添加编辑
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if (empty($data['cost_type_id'])){
                return parent::JsonReturn('缴费项不存在', 0);
            }
            if (empty($data['merchant_id'])){
                return parent::JsonReturn('请选择商户', 0);
            }
            if(empty($data['start_time'])||empty($data['end_time'])){
                return parent::JsonReturn('请选择起止时间', 0);
            }
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            if( $data['start_time']>$data['end_time']){
                return parent::JsonReturn('结束时间不能早于开始时间', 0);
            }
            Db::startTrans();
            try {
                $model =  new \app\common\model\tang\Cost();
                unset($data['__token__']);
                unset($data['date']);
                unset($data['file']);
                unset($data['merchant_type']);
                $erpCostId = (new CostType())->where('id',$data['cost_type_id'])->value('cost_type_id');

                if(empty($erpCostId)){
                    return parent::JsonReturn('暂未找到对应的费用项', 0);
                }
                $contractInfo = (new \app\common\model\tang\Merchant())->where('id',$data['merchant_id'])->field('id,code,uuid')->find();
                $amount = intval($data['amount'] * 100) ;
                $data['unit_price'] =  0.00 ;
                $data['number'] = 1 ;
                $data['amount'] = $amount;
                $data['all_amount'] = $amount;
                $data['real_amount'] =$amount;
                $data['contract_uuid'] =$contractInfo['uuid'];
                $data['contract_code'] =$contractInfo['code'];
//                $data['add_release_id'] ='$amount';//分配给谁收取
                $data['add_user'] = static::$admin_info['nickname'];
                $data['order_sn'] = OrderSn();
                $model->save($data);
                Db::commit();
                return self::JsonReturn("添加成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }
        $merchant_list  =getMerchant();
        $cost_type_list = (new CostType())->select();
        $id = $this->request->param("id/d");//父id
//        $service_charge = (\app\common\model\tang\System::where(['id'=>3])->value('amount'))/100;
        $service_charge = (\app\common\model\tang\SubjectList::where(['type'=>1])->value('rate'))/100;
        $info = $this->model->find($id);
        //分配物业人员收取费用
        $releaseUser = ReleaseUser::where('type',1)->select();
//        // 部门
        $department_list = SubjectList::where('type','=',2)->field('id,name')->select();
        //获取菜单列表
        $this->assign(compact("info", "id","merchant_list","releaseUser","department_list","cost_type_list","service_charge"));
        return $this->fetch();
    }

    public function detail()
    {
        $id = $this->request->param("id/d");//父id
        $info = $this->model->with(['costRule','merchants','costType'])->find($id);
        $info->time = date('Y-m-d H:i:s',$info->create_time);
        if($info->pay_status==0){
            $info->is_user = '未缴费';
            $info->fees_user = '未缴费';
        }else{
            switch ($info->is_user){
                case 0 :
                    $info->is_user =  '后台缴费';
                    $info->fees_user = $info->merchant->username;
                    break ;
                case 1 :
                    $info->is_user = '自主缴费';
                    $info->fees_user = $info->merchant->username;
                    break ;
            }
        }
        if(empty($info->add_user)){
            $info->add_user = $info->merchant->username;
        }
        switch ($info->pay_status){
            case -1 :
                $info->pay_status_name = '退费';
                break ;
            case 0 :
                $info->pay_status_name = '未支付';
                break ;
            case 1 :
                $info->pay_status_name = '已支付';
                break ;
        }
        $Subjectinfo = (new SubjectList())->where('id','=',$info->subject_id)->field('name')->find();
        $info->subject_id = $Subjectinfo['name'] ;
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }
    public function invoice()
    {
        $param = $this->request->param();
        $id   = intval($param['id']);
        $model =  new \app\common\model\tang\Cost();
        $cost = $model->find($id);
        if(empty($cost)){
            return self::ajaxResult([],0,1,'不存在的订单');
        }
        $invoice = empty($cost->invoice)?1:0;
        $update = $model->update(['invoice'=>$invoice],['id'=>$id]);
        if($update){
            return self::ajaxResult([],0,0,'修改成功');
        }else{
            return self::ajaxResult([],0,1,'修改失败');
        }

    }
}